/**
 * COPYRIGHT HangZhou Trustway Technology Company Limited
 * All right reserved.
 */
package com.robam.apollotest.apollotest.config;

import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @Description
 * @Author 薛铁琪
 * @CreateTime 2020-10-09 15:34
 * @Version 1.0
 */
@Component
@Slf4j
public class ApolloConfigChanged implements ApplicationContextAware {
    private static final String LOGGER_TAG = "logging.level.";
    @Autowired
    private LoggingSystem loggingSystem;

    private ApplicationContext applicationContext;

    @ApolloConfigChangeListener
    private void someChangeHandler(ConfigChangeEvent changeEvent) {
        for (String key : changeEvent.changedKeys()) {
            if (key.startsWith(LOGGER_TAG)) {
                ConfigChange configChange = changeEvent.getChange(key);
                String oldValue = configChange.getOldValue();
                String newValue = configChange.getNewValue();

                LogLevel level = LogLevel.valueOf(newValue.toUpperCase());
                loggingSystem.setLogLevel(key.replace(LOGGER_TAG, ""), level);

                log.info("【Apollo动态修改日志级别】changedKey:【{}】, oldValue=【{}】, newValue:【{}】", key, oldValue, newValue);
            }

            ConfigChange change = changeEvent.getChange(key);
            log.info("Found change - {}", change.toString());
        }

        // 更新相应的bean的属性值，主要是存在@ConfigurationProperties注解的bean
        this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}